import { lazyReportBatch } from "../report";

export default function observerEntries() {
  //页面资源加载情况
  if (document.readyState === "complete") {
    observeEvent();
  } else {
    const onLoad = () => {
      observerEvent();
      window.removeEventListener("load", onLoad, true);
    };
    window.addEventListener("load", onLoad, true);
  }
}

export function observerEvent() {
  //监听页面上所有的资源加载情况
  const entryHanndler = (list) => {
    for (const entry of list.getEntries()) {
      if (observer) {
        observer.disconnect();
      }
      const reportData = {
        name: entry.name, //资源名字
        //什么类型的数据
        type: "performance",
        //当前的子类型
        subType: entry.entryType,
        sourceType: entry.initiatorType, //资源类型
        duration: entry.duration, //加载时间
        dns: entry.domainLookupEnd - entry.domainLookupStart, //dns解析时间
        tcp: entry.connectEnd - entry.connectStart, //tcp连接时间
        ttfb: entry.responseStart, //首字节时间
        protocol: entry.nextHopProtocol, //请求协议
        responseBodySize: entry.encodedBodySize, //响应内容大小
        responseHeaderSize: entry.transferSize - entry.encodedBodySize, //响应头大小
        transferSize: entry.transferSize, //请求内容大小
        resourceSize: entry.decodedBodySize, //资源解压后大小
        startTime: performance.now(), //开始时间
      };
      lazyReportBatch(reportData);
    }
  };
  let observer = new PerformanceObserver(entryHanndler);
  observer.observe({ type: ["resource"], buffered: true });
}
